<?php

namespace addons\Merchants\services;

use Yii;
use yii\web\NotFoundHttpException;
use common\enums\StatusEnum;
use common\components\Service;
use common\helpers\StringHelper;
use common\helpers\AddonHelper;
use Overtrue\Pinyin\Pinyin;
use addons\Merchants\common\models\Addons;

/**
 * Class AddonsService
 * @package services\common
 * @author YiiFrame <21931118@qq.com>
 */
class AddonsService extends Service
{

    public function update($name, $config)
    {
        if (!($model = $this->findByName($name))) {
            $model = new Addons();
        }

        $model->attributes = $config->info;
        $model->is_setting = $config->isSetting ? StatusEnum::ENABLED : StatusEnum::DISABLED;
        $model->is_rule = $config->isRule ? StatusEnum::ENABLED : StatusEnum::DISABLED;
        $model->is_merchant_route_map = $config->isMerchantRouteMap ? StatusEnum::ENABLED : StatusEnum::DISABLED;
        $model->group = $config->group;
        $model->bootstrap = $config->bootstrap ?? '';
        $model->service = $config->service ?? '';
//        $model->default_config = $default_config;
        $model->console = $config->console ?? [];
        $model->wechat_message = $config->wechatMessage;
        $model->merchant_id = Yii::$app->user->identity->merchant_id;
        $model->updated_at = time();
        // 首先字母转大写拼音
        if (($chinese = StringHelper::strToChineseCharacters($model->title)) && !empty($chinese[0])) {
            $title_initial = mb_substr($chinese[0][0], 0, 1, 'utf-8');
            $model->title_initial = ucwords((new Pinyin())->abbr($title_initial));
        }

        if (!$model->save()) {
            throw new NotFoundHttpException($this->getError($model));
        }

        // 更新缓存
        Yii::$app->services->addons->updateCacheByName($name);

        return $model;

        return $model;
    }


    public function findByName($name)
    {
        return Addons::find()
            ->where(['name' => $name, 'status' => StatusEnum::ENABLED,'merchant_id'=>Yii::$app->user->identity->merchant_id])
            ->one();
    }

    /**
     * 获取本地插件列表
     *
     * @return array
     */
    public function getLocalList()
    {
        $addonDir = Yii::getAlias('@addons');

        // 获取插件列表
//        $dirs = array_map('basename', glob($addonDir . '/*'));
        $dirs = \common\models\common\Addons::find()
            ->where(['!=','group','plug'])
            ->select('name')->column();
        foreach ($dirs as $i=>$value){
            if($value=='Merchants')
                unset($dirs[$i]);
        }
        $list = Addons::find()
            ->where(['merchant_id'=>Yii::$app->user->identity->merchant_id])
            ->asArray()
            ->all();

        $tmpAddons = [];
        foreach ($list as $addon) {
            $tmpAddons[$addon['name']] = $addon;
        }

        $addons = [];
        foreach ($dirs as $value) {
            // 判断是否安装
            if (!isset($tmpAddons[$value])) {
                $class = AddonHelper::getAddonConfig($value);

                // 实例化插件失败忽略执行
                if (class_exists($class)) {
                    $config = new $class;
                    $addons[$value] = $config->info;
                }
            }
        }

        return $addons;
    }
}